import axios, {AxiosRequestConfig} from "axios";
import {message, notification} from "antd";
import store from "store2";
import _ from "lodash";
import URI from "urijs";
import {IResponse} from "@/common/common";
import LoginStore from "@/common/store/LoginStore";

axios.defaults.timeout = 10000;
axios.defaults.validateStatus = () => true;
axios.defaults.headers.post["Content-Type"] = "application/json;charset=utf-8";
axios.defaults.headers.get["Content-Type"] = "application/json;charset=utf-8";

function checkStatus(result: any) {
  return new Promise<IResponse>((resolve) => {
    if (result.status === 200) {
      const code = result.data.code;
      if (code === 401) {
        LoginStore.logout();
      } else {
        if (code <= 400) {
          // else if (code === 403) {
          //   // message.warning("您没有操作权限");
          // } else if (code === 404) {
          //   // message.error("服务请求404失败");
          // }
          resolve(result.data);
        } else if (code === 500) {
          resolve(result.data);
        } else {
          resolve(result.data);
        }
      }
    } else {
      message.error(result.status + ": " + result.statusText);
      resolve({
        code: result.status,
        message: result.statusText,
      });
    }
  });
}

function checkData(data: IResponse) {
  return data || {code: -1};
}

export interface RequestConfig extends AxiosRequestConfig {
  useCache?: boolean;
  ignoreAuth?: boolean;
  token?: string;
}

const auth_whitelist = ["/app/auth/login", "/app/logout"];

export function checkExpire(config: RequestConfig) {
  if (config.ignoreAuth || !config.url) {
    return false;
  }
  if (auth_whitelist.includes(config.url)) {
    return false;
  }
  if (!config.headers) {
    config.headers = {};
  }
  if (!setToken(config.headers)) {
    return true;
  }
  const taskType = config.params?.type || config.data?.type;
  if (taskType) {
    config.headers["groupCode"] = taskType;
  }
  return false;
}

// export function getUserInfo(): IUser | undefined {
//   const userInfo = store.get(storeKey.userInfo);
//   if (userInfo && !_.isEmpty(userInfo)) {
//     return userInfo;
//   }
//   loginStore.logout();
//   return undefined;
// }

export function setToken(header: any) {
  // const user = getUserInfo();
  // if (!user) {
  //   return false;
  // }
  // header["SAAS-TOKEN"] = user.token;
  return true;
}

export default (config: RequestConfig) => {
  if (checkExpire(config)) {
    return new Promise<any>((resolve, reject) => {
      resolve({} as any);
    });
  }

  if (!config.method || config.method.toUpperCase() === "GET") {
    addUrlQuery(config);
  }

  return axios(config)
    .then(checkStatus)
    .then(checkData)
    .catch((err) => err)
}

export function addUrlQuery(config: RequestConfig) {
  let uri = URI(config.url);
  if (config.params) {
    for (const p of Object.keys(config.params)) {
      if (p && config.params[p] !== undefined) {
        const para: any = {};
        para[p] = config.params[p];
        uri.addQuery(para);
      }
    }
    delete config.params;
  }
  if (!config.useCache && !config.params?.useCache) {
    uri = uri.addQuery({timestamp: Date.now()});
  }
  config.url = uri.readable();
}
